package com.raising.modules.sys.controller;

import com.raising.framework.controller.BaseController;
import com.raising.framework.shiro.MyFormAuthenticationFilter;
import com.raising.modules.sys.entity.Role;
import com.raising.modules.sys.service.RoleService;
import com.raising.utils.JStringUtils;
import com.raising.utils.UserUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 首页控制器
 * 判断当前登录用户跳转的主页
 * @author gaoy
 */
@Controller
@RequestMapping(value = "check")
public class LoginCheckController extends BaseController {

	@Autowired
	private RoleService roleService;

	/**
	 * 登录成功后的校验跳转路径
	 * @see MyFormAuthenticationFilter#onLoginSuccess(AuthenticationToken,Subject,ServletRequest,ServletResponse)
	 * @author gaoy
	 * 2017 2017-5-9 上午10:20:41
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String check(HttpServletRequest request, Model model,String jumpUrl) {
		String userName = UserUtils.getUserName();
		if(userName!=null){
			//获取需要跳转的路径
			if(JStringUtils.isNotBlank(jumpUrl)){
				return "redirect:" + jumpUrl;
			}
			//默认页面展示路径
			List<String> roleList = UserUtils.getLoginUser().getRoleIds();
			String firstRole = roleList.get(0);
			//根据角色查询默认首页路径
			try {
				Role role = roleService.get(firstRole);
				if( role == null ){
//					return "redirect:" + "front/home";
					return "signin";
				}
				String siteUrl = role.getSiteUrl();
				olog("登录并进入系统");
				return "redirect:" + siteUrl;
			}catch (Exception e){
//				return "redirect:" + "front/home";
				return "signin";
			}
		}
		return "signin";
	}
	


	

}
